package cdu.javaendwork.Controller.LoginAndRegister;

import cdu.javaendwork.dao.Universal;
import cdu.javaendwork.dao.impl.UniversalImpl;
import cdu.javaendwork.model.sqlModel.User;
import cdu.javaendwork.service.Impl.User.UserServiceImpl;
import cdu.javaendwork.service.Interface.User.UserService;
import cdu.javaendwork.util.ProNumber.ProNumBerHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;
@WebServlet("/register")
public class RegisterController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset = utf-8");
        User user=null;

        //保存照片位置
        String path = "/WEB-INF/photo";
        //获取真实对应的地址
        String photoUrl = req.getServletContext().getRealPath(path);
        System.out.println(photoUrl);
        //创建一个基于磁盘文件系统的工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传处理器
        ServletFileUpload upload =new ServletFileUpload(factory);
        try {
            //解析请求
            List<FileItem> items = upload.parseRequest(req);
            if(!items.isEmpty()){
                user = new User();
            }

            //创建迭代器，准备处理表单数据
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()){
                FileItem item = iterator.next();
                if(item.isFormField()){
                    if(item.getFieldName().equals("username")){
                        user.setUsername(item.getString("utf-8"));
//                        candidate.setName(new String(item.getString().getBytes("iso-8859-1"),"utf-8"));
                    }
                    if(item.getFieldName().equals("password")){
                        user.setPassword(item.getString("utf-8"));
                    }
                    if(item.getFieldName().equals("userprofile")){
                        user.setUserprofile(item.getString("utf-8"));
                    }
                    if(item.getFieldName().equals("phone")){
                        user.setPhone(item.getString("utf-8"));
                    }
                }else {
                    String fileName = item.getName();
                    //防止重复的日期前缀
                    ProNumBerHelper proNumBerHelper = new ProNumBerHelper();
                    String pro = proNumBerHelper.getProNumBerForDate(new Timestamp(new java.util.Date().getTime()).toString());
                    File file = new File(photoUrl+"//"+pro+fileName);
                    item.write(file);
                    user.setPhoto(req.getContextPath()+path+"/"+pro+fileName);
                }
            }
        } catch (Exception e) {
            System.out.println("上传文件出错："+e.getMessage());
        }

        PrintWriter out = resp.getWriter();
        UserService userService=new UserServiceImpl();
        Universal universal=new UniversalImpl();
        //  User user1=userService.isRegister(user.getName());
        User user1=null;
        List<User> list = universal.filter("User","username='"+user.getUsername()+"'");
        if(!list.isEmpty()){
            user1=list.get(0);
        }

        if(user.getUsername()==null||user.getPassword()==null||user.getUsername().equals("")||user.getPassword().equals("")){
            out.println("<script>alert('注册失败!信息不能为空！');window.location.href='register.jsp'</script>");
        }else if(user1!=null){
            out.println("<script>alert('注册失败！用户名有一样的了');window.location.href='register.jsp'</script>");
        } else {
            if(!userService.insert(user.getUsername(),user.getPassword(),user.getPhoto(),user.getUserprofile(),user.getPhone(),1)){
                out.println("<script>alert('注册失败！');window.location.href='register.jsp'</script>");
            }else{
                HttpSession session = req.getSession();
                session.setAttribute("user",user);
                out.println("<script>alert('注册成功！');window.location.href='/'</script>");
            }
        }
    }
}
